package com.livepass.android.girlspicks.helps;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.livepass.android.girlspicks.adapters.ArticleTableAdapter;

public class DBHelper extends SQLiteOpenHelper {
	private static final String DATABASE_NAME = "article.db";
	private static final int DATABASE_VERSION = 1;
	private String DB_PATH;
	private SQLiteDatabase dataBase;
	private Context mContext;

	@SuppressLint("SdCardPath")
	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		DB_PATH = "/data/data/"
				+ context.getApplicationContext().getPackageName()
				+ "/databases/";
		mContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(ArticleTableAdapter.CREATE_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		// onCreate(database);
		if (oldVersion == 1) {
			database.execSQL("DROP TABLE " + ArticleTableAdapter.TABLE_NAME);
			database.execSQL(ArticleTableAdapter.CREATE_TABLE);
		}
	}

	@Override
	public synchronized void close() {
		if (dataBase != null)
			dataBase.close();
		super.close();
	}

	public boolean createDataBase() {
		boolean dbExist = checkDataBase();
		if (!dbExist) {
			this.getReadableDatabase();
			try {
				Log.d("DATABASE_LOG", "Overrided");
				copyDataBase();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	private boolean checkDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + DATABASE_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			if (checkDB != null) {
				checkDB.close();
			}
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;

	}

	private void copyDataBase() throws IOException {
		InputStream myInput = mContext.getAssets().open(DATABASE_NAME);
		String outFileName = DB_PATH + DATABASE_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

}
